/*
*  SkyOpenALBuffer.cpp
*  
*
*  Created by Alexander Trutchenko on 11/02/12.
*  Copyright 2012 Free Team. All rights reserved.
*
*/

#include "SkyOpenALBuffer.h"


//#include "SkyFileUtils.h"
//#include "SkyFile.h"
#include "SkyAssert.h"
//#include "SkyConfig.h"
//#include "SkySoundDecoder.h"
//#include "SkyOpenALInclude.h"


namespace sky {

////////////////////////////////////////////////////////
//
/** SkyOpenALBuffer
*  
*/
////////////////////////////////////////////////////////

SkyOpenALBuffer::SkyOpenALBuffer(ALuint bufferID, const char* file)
: _header(file)
, _bufferID(bufferID)
, _isOk(true)  
{
	ALint value;
	alGetBufferi(_bufferID, AL_FREQUENCY, &value);
	_header.frequency = value;
	alGetBufferi(_bufferID, AL_SIZE, &value);
	_header.decodedSize = value;
	
	alGetBufferi(_bufferID, AL_CHANNELS, &value);
	ALint valueBits;
	alGetBufferi(_bufferID, AL_BITS, &valueBits);
	if (value == 1)
	{
		if (valueBits == 8)
			_header.format = AL_FORMAT_MONO8;
		else // valueBits == 16
			_header.format = AL_FORMAT_MONO16;
	}
	else // value == 2
	{
		if (valueBits == 8)
			_header.format = AL_FORMAT_STEREO8;
		else // valueBits == 16
			_header.format = AL_FORMAT_STEREO16;
	}
}

SkyOpenALBuffer::SkyOpenALBuffer()
: _header("")
, _bufferID(AL_NONE)
, _isOk(false)
{
	// Generate Buffers
	alGetError(); // clear error code
	alGenBuffers(1, &_bufferID);
	ALenum error = alGetError();
	if (error != AL_NO_ERROR)
	{
		SkyAssert(false, "SkyOpenALBuffer::SkyOpenALBuffer(): Can't create OpenAL buffer, error");
		return;
	}
	_isOk = true;
}

SkyOpenALBuffer::~SkyOpenALBuffer()
{
	if (_isOk)
		alDeleteBuffers(1, &_bufferID);
}

bool SkyOpenALBuffer::setData(const ALvoid* decodedData, const SkyBufferHeader& header)
{
	alGetError();
	alBufferData(_bufferID, header.format, decodedData, header.decodedSize, header.frequency);
	ALenum err = alGetError();
	if (err != AL_NO_ERROR)
	{
		SkyAssert(false, "SkyOpenALBuffer::setData(): Can't set buffer data (may be because this buffer is connected to any source)!");
		return false;
	}
	_header = header;
	return true;
}



} // namespace sky
